package com.gujiangbo.application.common.conf;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.GetDataBuilder;
import org.apache.curator.framework.api.SetDataBuilder;
import org.apache.curator.utils.EnsurePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.gujiangbo.application.common.base.ZKClientPool;

@Component
@PropertySources({@org.springframework.context.annotation.PropertySource({"classpath:config/base/common-conf.properties"})})
@Repository("confClient")
public class ConfClient
{
  @Autowired
  private ZKClientPool zkCliPool;
  @Value("${common-conf.zk.ns}")
  private String _NAMESPACE;
  @Value("${common-conf.zk.cli.key}")
  private String _CLIENT_KEY;
  
  public boolean save(String key, String value)
  {
    try
    {
      CuratorFramework cli = this.zkCliPool.getClient(this._CLIENT_KEY, this._NAMESPACE);
      cli.newNamespaceAwareEnsurePath(getNodePathByKey(key)).ensure(cli.getZookeeperClient());
      cli.setData().forPath(getNodePathByKey(key), value.getBytes());
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return false;
    }
    return true;
  }
  
  public boolean remove(String key)
  {
    return true;
  }
  
  public String get(String key)
  {
    try
    {
      byte[] data = (byte[])this.zkCliPool.getClient(this._CLIENT_KEY, this._NAMESPACE).getData().forPath(getNodePathByKey(key));
      return new String(data);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
  
  public CuratorFramework getCli()
  {
    return this.zkCliPool.getClient(this._CLIENT_KEY, this._NAMESPACE);
  }
  
  public String getNodePathByKey(String key)
  {
    return "/" + key.replaceAll("\\.", "/");
  }
}